package com.mt.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    private static final String LOGIN_URL="http://localhost:9111/user-auth/oauth/toLogin";



    @Autowired
    private AuthService authService;


    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.获取响应对象
        System.out.println("网关001");

        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        return chain.filter(exchange);

      /*
        //3.判断当前的请求是否为登录请求,如果是,则直接放行
        if (request.getURI().getPath().contains("/admin/login")||request.getURI().getPath().contains("/v2/api-docs")||"/user-auth/oauth/login".equals(path)||"/user-auth/oauth/toLogin".equals(path)){
            //放行
            return chain.filter(exchange);
        }
        if (path.contains("user")||path.contains("user-auth")||path.contains("order-web")||path.contains("api")||path.contains("order")){




            //2.从cookie中获取jti的值,如果该值不存在,拒绝本次访问
            String jti = authService.getJtiFromCookie(request);
            if (StringUtils.isEmpty(jti)){
                //拒绝访问
            *//*response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();*//*
                //跳转登录页面

                String query="";
                if (request.getURI().getQuery()!=null&&request.getURI().getQuery().length()>1){
                    String   ss=request.getURI().getQuery();

                    String replace = ss.replace("&", "===");
                    query="?"+replace;

                }

                return this.toLoginPage(LOGIN_URL+"?FROM="+request.getURI().getPath()+query,exchange);
            }

            //3.从redis中获取jwt的值,如果该值不存在,拒绝本次访问
            String jwt = authService.getJwtFromRedis(jti);
            if (StringUtils.isEmpty(jwt)){
                //拒绝访问
            *//*response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();*//*
                return  this.toLoginPage(LOGIN_URL,exchange);
            }

            //4.对当前的请求对象进行增强,让它会携带令牌的信息
            request.mutate().header("Authorization","Bearer "+jwt);

            if (path.contains("/order-web/wcart")){
                redisTemplate.opsForValue().set("myurl",path.split("/")[1],25,TimeUnit.SECONDS);
            }



            return chain.filter(exchange);
        }



        //4.获取当前的所有请求头信息
        HttpHeaders headers = request.getHeaders();

        //5.获取jwt令牌信息
        String jwtToken = headers.getFirst("token");

        //6.判断当前令牌是否存在,
        if (StringUtils.isEmpty(jwtToken)){
            //如果不存在,则向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //6.1 如果令牌存在,解析jwt令牌,判断该令牌是否合法,如果令牌不合法,则向客户端返回错误提示信息
        try {
            //解析令牌
            JwtUtil.parseJWT(jwtToken);
        }catch (Exception e){
            e.printStackTrace();
            //令牌解析失败
            //向客户端返回错误提示信息

            response.setStatusCode(HttpStatus.UNAUTHORIZED);

            return response.setComplete();

        }

        //6.2 如果令牌合法,则放行
        return chain.filter(exchange);*/
    }



    //跳转登录页面
    private Mono<Void> toLoginPage(String loginUrl, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location",loginUrl);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
